//
//  OrderViewController.m
//  cm
//
//  Created by suyibaishan on 2017/11/5.
//  Copyright © 2017年 feihu. All rights reserved.
//

#import "OrderViewController.h"
#import "OrderCell.h"
#import "OrderDetailViewController.h"

@interface OrderViewController () <UITableViewDelegate,UITableViewDataSource>
{
    UITableView *_tableView;
    NSMutableArray *dataSource;
    NSInteger state;
    MBProgressHUD *HUD;
     NSInteger page;
}
@end

@implementation OrderViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self reloadData];
    
    [self createOrderView];
}

-(void)reloadData
{
    [[ToolNet sharedManager] getOrderData:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] pageNum:1 pageSize:16 url:MOrderData completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            [dataSource removeAllObjects];
            [dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
            [_tableView reloadData];
            page = 2;
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
    }];
}

-(void)loadMoreData
{
    [[ToolNet sharedManager] getOrderData:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] pageNum:page pageSize:16 url:MOrderData completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        if ([responseJson[@"code"] isEqual:@1]) {
            if ([responseJson[@"data"][@"pages"] integerValue] >= page) {
                [dataSource addObjectsFromArray:responseJson[@"data"][@"list"]];
                [_tableView.mj_footer endRefreshing];
                page++;
            }
            else{
                [_tableView.mj_footer endRefreshingWithNoMoreData];
            }
            [_tableView reloadData];
        }
        else {
            [self showMessage:responseJson[@"msg"]];
            [_tableView.mj_footer endRefreshing];
        }
    }];
}

-(void)createOrderView
{
    self.titleLabel.text = @"我的订单";
    self.backButton.hidden = NO;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.baseBarHeight, kScreenWidth, kScreenHeight - self.baseBarHeight) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self reloadData];
    }];
    _tableView.mj_header.automaticallyChangeAlpha = YES;
    _tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];

    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [self.view addSubview:HUD];
    
    dataSource = [NSMutableArray array];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self reloadData];
}

#pragma - UITableViewDataSource,UITableViewDelegate
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return dataSource.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier =  @"indentifier";
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell)
    {
        cell = [[OrderCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.model = [[OrderModel alloc] initWithDictionary:dataSource[indexPath.section]];
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
    orderDetailVC.orderId = [dataSource[indexPath.section][@"id"] integerValue];
    [self.navigationController pushViewController:orderDetailVC animated:YES];
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 50)];
    view.backgroundColor = [UIColor whiteColor];
    
    UIView *grayline = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 10)];
    grayline.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [view addSubview:grayline];
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = [NSString stringWithFormat:@"订单编号：%@",dataSource[section][@"orderNo"]];
    titleLabel.textColor = [UIColor blackColor];
    titleLabel.font = [UIFont systemFontOfSize:13];
    [view addSubview:titleLabel];
    titleLabel.sd_layout
    .leftSpaceToView(view, 10)
    .topSpaceToView(grayline, 10)
    .widthIs(kScreenWidth - 90)
    .heightIs(20);
    
    UILabel *stateLabel = [[UILabel alloc] init];
    stateLabel.font = [UIFont systemFontOfSize:13];
    stateLabel.textAlignment = NSTextAlignmentRight;
    stateLabel.textColor = [UIColor colorWithRed:0.99 green:0.33 blue:0.16 alpha:1];
    [view addSubview:stateLabel];
    stateLabel.sd_layout
    .rightSpaceToView(view, 10)
    .topSpaceToView(grayline, 10)
    .widthIs(100)
    .heightIs(20);


    state = [dataSource[section][@"state"] integerValue];
    if (state == 0) {
        stateLabel.text = @"待审核";
    }
    else if (state == 1) {
        stateLabel.text = @"订单驳回";
    }
    else if (state == 2) {
        stateLabel.text = @"订单完成";
    }
    else if (state == 3) {
        stateLabel.text = @"订单作废";
    }
    
    return view;
}

-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    view.backgroundColor = [UIColor whiteColor];

    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 1)];
    line.backgroundColor = [UIColor colorWithRed:0.96 green:0.96 blue:0.96 alpha:1];
    [view addSubview:line];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancelBtn setTitle:@"删除订单" forState:UIControlStateNormal];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:13];
    [cancelBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    cancelBtn.layer.borderWidth = 1;
    cancelBtn.tag = section;
    [cancelBtn addTarget:self action:@selector(cancelBtnPressed:) forControlEvents:UIControlEventTouchUpInside];
    [view addSubview:cancelBtn];
    cancelBtn.sd_layout
    .rightSpaceToView(view, 10)
    .topSpaceToView(view, 9)
    .widthIs(75)
    .heightIs(22);
    
    state = [dataSource[section][@"state"] integerValue];
    if (state == 3) {
//        view.frame = CGRectMake(0, 0, kScreenWidth, 40);
        cancelBtn.hidden = NO;
    }
    else {
        cancelBtn.hidden = YES;
//        view.frame = CGRectMake(0, 0, kScreenWidth, 0.01);
    }
    
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 50;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    state = [dataSource[section][@"state"] integerValue];
    if (state == 3) {
        return 40;
    }
    return 0.01;
}

-(void)cancelBtnPressed:(UIButton *)button
{
    [HUD show:YES];
    [[ToolNet sharedManager] managerOrders:[mUserDefaults objectForKey:@"userCode"] accessToken:[mUserDefaults objectForKey:@"accessToken"] orderId:[dataSource[button.tag][@"id"] integerValue] url:MDelOrder completionHandler:^(NSURLSessionDataTask *task, NSDictionary *responseJson, NSError *error) {
        [HUD hide:YES];
        if ([responseJson[@"code"] isEqual:@1]) {
            [self reloadData];
        }
        else {
            [self showMessage:responseJson[@"msg"]];
        }
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
